#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import datetime

from farado.ui.renderer import view_renderer
from farado.general_manager_holder import gm_holder
from farado.helpers.cookie_helper import current_session_id


class UiUserRestrictions:
    def __init__(self, **args) -> None:
        for key, value in args.items():
            setattr(self, key, value)
    def __repr__(self):
        result = '<UiUserRestrictions(\n'
        for key, value in self.__dict__.items():
            result += f'''{key}='{value}'\n'''
        result += ')>'
        return result

class BaseView:
    def __init__(self):
        # aliases
        self.project_rights = gm_holder.permission_manager.project_rights
        self.is_admin = gm_holder.permission_manager.check_is_admin

    # overridden by the logic above
    def process_function(self, user, function):
        pass

    def current_user(self):
        return gm_holder.permission_manager.user_by_session_id(
            current_session_id()
        )

    def login_and_open(self, path="", args={}):
        return view_renderer["login"].render(
            function=f'{self.name}{path}',
            args=args,
        )

class DataTableArgs:
    class Column:
        def __init__(
                self,
                number=0,
                data="",
                name="",
                searchable=False,
                orderable=False,
                search_value="",
                search_regex=False,
                ) -> None:
            self.number = number
            self.data = data
            self.name = name
            self.searchable = searchable
            self.orderable = orderable
            self.search_value = search_value
            self.search_regex = search_regex

    def __init__(self, args) -> None:
        self._args = args
        self.draw = get_int_value(args, 'draw', 1)
        self.start = get_int_value(args, 'start', 0)
        self.length = get_int_value(args, 'length', 10)
        self.search_value = get_value(args, 'search[value]', '')
        self.order_column = get_int_value(args, 'order[0][column]', 0)
        self.is_order_ascending = get_bool_value(args, 'order[0][dir]', 'asc', True)
        self.columns = []
        for column_number in range(64):
            if (not f'columns[{column_number}][data]' in args or
                not f'columns[{column_number}][name]' in args or
                not f'columns[{column_number}][searchable]' in args or
                not f'columns[{column_number}][orderable]' in args or
                not f'columns[{column_number}][search][value]' in args or
                not f'columns[{column_number}][search][regex]' in args):
                    break
            self.columns.append(DataTableArgs.Column(
                number=column_number,
                data=args[f'columns[{column_number}][data]'],
                name=args[f'columns[{column_number}][name]'],
                searchable=bool(args[f'columns[{column_number}][searchable]'] == 'true'),
                orderable=bool(args[f'columns[{column_number}][orderable]'] == 'true'),
                search_value=args[f'columns[{column_number}][search][value]'],
                search_regex=bool(args[f'columns[{column_number}][search][regex]'] == 'true'),
            ))

    def __repr__(self):
        return json.dumps(self._args, indent=2)

    def slice_ids(self, ids):
        return ids[self.start: self.start + self.length]

def bring_value(value, default_value):
    if value:
        return value
    return default_value

def get_value(args, name, default_value):
    if name in args:
        return args[name]
    return default_value

def get_int_value(args, name, default_value):
    if name in args:
        value = args[name]
        if value.isdigit():
            return int(value)
    return default_value

def get_bool_value(args, name, compare_with, default_value):
    if name in args:
        return bool(args[name] == compare_with)
    return default_value

def get_date_value(args, name, default_value=datetime.date(1970, 1, 1)):
    if name in args:
        value = args[name]
        try:
            return datetime.date.fromisoformat(value)
        except:
            pass
    return default_value

def get_values(args, name):
    if name in args:
        value = args[name]
        if type(value) == list:
            return value
        return [value]
    return []
